<template>
  <!-- 底部 -->
  <div class="my-footer">
    <!-- 全选 -->
    <div class="custom-control custom-checkbox">
      <input
        v-model="isAll"
        type="checkbox"
        class="custom-control-input"
        id="footerCheck"
      />
      <label class="custom-control-label" for="footerCheck">全选</label>
    </div>
    <!-- 合计 -->
    <div>
      <span>合计:</span>
      <span class="price">¥ {{ allPrice }}</span>
    </div>
    <!-- 按钮 -->
    <button type="button" class="footer-btn btn btn-primary">
      结算 ( {{ allCount }} )
    </button>
  </div>
</template>

<script>
export default {
  props: {
    list: Array,
    required: true
  },
  data () {
    return {
      // allPrice: 0,
      // allCount: 0
    }
  },
  computed: {
    isAll: {
      set (val) {
        this.list.forEach(item => (item.goods_state = val))
      },
      get () {
        //根据小选框的选中状态来决定
        //如果全部选中就返回true
        //只要有一个没选中就返回false
        if (this.list.length === 0) return false
        return this.list.every(item => item.goods_state === true)
      }
    },
    allCount () {
      //1.reduce 方法
      // return this.list.reduce((sum, item) => {
      //   if (item.goods_state === true) {
      //     //选中商品才累加数量
      //     sum += item.goods_count
      //   }
      //   return sum
      // }, 0)

      //2.forEach 方法
      let sum = 0
      this.list.forEach(item => {
        if (item.goods_state) {
          sum += item.goods_count
        }
      })
      return sum

      //3.filter 和 reduce 方法结合使用
      // return this.list.filter(item=>item.goods_state).reduce((sum,item)=>sum+=item.goods_state,0)
    },
    allPrice () {
      //1.reduce方法
      // return this.list.reduce((sum, item) => {
      //   if (item.goods_state === true) {
      //     //选中商品才累加价格
      //     sum += item.goods_count * item.goods_price
      //   }
      //   return sum
      // }, 0)

      //2.forEach 方法
      // let sum = 0
      // this.list.forEach(item => {
      //   if (item.goods_state) {
      //     sum += item.goods_count * item.goods_price
      //   }
      // })
      // return sum

      // 3.filter 和 reduce 结合使用
      return this.list
        .filter(item => item.goods_state)
        .reduce((sum, item) => (sum += item.goods_count * item.goods_price), 0)
    }
  },
  methods: {}
}
</script>

<style lang="less" scoped>
.my-footer {
  position: fixed;
  z-index: 2;
  bottom: 0;
  width: 100%;
  height: 50px;
  border-top: 1px solid #ccc;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
  background: #fff;

  .price {
    color: red;
    font-weight: bold;
    font-size: 15px;
  }
  .footer-btn {
    min-width: 80px;
    height: 30px;
    line-height: 30px;
    border-radius: 25px;
    padding: 0;
  }
}
</style>
